<template>
    <div>
        <el-dialog v-model="dialogVisible" width="60%" align-center :close-on-click-modal="false" :show-close="false"
            :before-close="handleClose" destroy-on-close draggable>
            <template #header="{ close }">
                <div class="dialog-header flex justify-between items-center">
                    <div>评审方案{{ ruleForm.id ? '编辑' : '新增' }}</div>
                    <el-icon class="el-icon--left cursor-pointer" @click="close">
                        <CircleCloseFilled color="#fff" />
                    </el-icon>
                </div>
            </template>
            <el-form :model="ruleForm" :rules="rules" label-width="130px" ref="ruleFormRef">
                <!-- 基本信息 -->
                <div class="bg-white mt-[10px]">
                    <BaseHead>基本信息</BaseHead>
                    <div class="p-[10px]">

                        <el-row :gutter="20">

                            <el-col :span="12">
                                <el-form-item label="评审方案名称" prop="name">
                                    <el-input placeholder="请输入评审方案名称" v-model="ruleForm.name" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12"></el-col>
                            <el-col :span="12">
                                <el-form-item label="满分" prop="fullMark">
                                    <el-input type="number" v-model="ruleForm.fullMark" @input="validateNumber"
                                        clearable>
                                        <template #append>（分）</template></el-input>
                                </el-form-item></el-col>

                        </el-row>
                    </div>
                </div>
                <!-- 评审标准 -->
                <div class="bg-white mt-[10px]">
                    <BaseHead>评审标准 <template v-slot:Rslot>
                            <el-button @click="addBz">添加标准</el-button>
                        </template></BaseHead>
                    <div class="p-[10px]">
                        <el-table :data="ruleForm.reviewStandardDTOs" border style="width: 100%">
                            <el-table-column align="center" label="一级标准" width="600">
                                <template #default="scope">

                                    <el-form-item label-width="0" :prop="'reviewStandardDTOs.' + scope.$index + '.name'"
                                        :rules="{ required: true, message: '必填', trigger: 'blur' }">
                                        <div class="flex items-center"><el-input v-model="scope.row.name" />
                                            <span class="addText" @click="addLv2(scope.$index)">添加二级标准</span>
                                        </div>
                                    </el-form-item>


                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="二级标准">
                                <template #default="scope">
                                    <el-form-item label-width="0"
                                        :prop="'reviewStandardDTOs.' + scope.$index + '.lvl2Names.' + index + '.value'"
                                        :rules="{ required: true, message: '必填', trigger: 'blur' }"
                                        v-for="(item, index) in scope.row.lvl2Names" :key="index">
                                        <el-input v-model="item.value" class="mt-[10px]" />
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="分数" width="120">
                                <template #default="scope">
                                    <el-form-item label-width="0"
                                        :prop="'reviewStandardDTOs.' + scope.$index + '.lvl2Marks.' + index + '.value'"
                                        :rules="{ required: true, message: '必填', trigger: 'blur' }"
                                        v-for=" (item, index) in scope.row.lvl2Marks" :key="index">
                                        <el-input v-model="item.value" type="number" class="mt-[10px]" />
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="操作">
                                <template #default="scope">
                                    <el-link type="primary" :underline="false" @click="delBz(scope.$index)">删除</el-link>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <div class="operate-btns">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
                        <el-button type="primary" @click="closeMet">关闭</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import { reviewSchemeAdd, getreviewSchemeUpdate } from "@/api/achievement/cghj"
import { ElMessage, ElMessageBox } from "element-plus";
import cloneDeep from 'lodash/cloneDeep';
const dialogVisible = defineModel();
const ruleForm = reactive({
    name: '',
    fullMark: '',
    businessType: 'project',
    reviewStandardDTOs: [{
        name: '',
        lvl2Names: [{ value: '' }],
        lvl2Marks: [{ value: '' }]
    }]
})
const rules = reactive({
    name: [
        { required: true, message: '请输入评审方案名称', trigger: 'blur' },
    ],
    fullMark: [
        { required: true, message: '请输入满分', trigger: 'blur' },
    ],
})


const ruleFormRef = ref()
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            let totleNum = 0
            ruleForm.reviewStandardDTOs.forEach(element => {
                element.lvl2Marks.forEach(element2 => {
                    totleNum += Number(element2.value)
                });
            });
            if (totleNum != ruleForm.fullMark) {
                return ElMessage({
                    message: '评审标准总分与满分不相等！',
                    type: 'error',
                })
            }
            let params = {
                ...ruleForm,
            }
            params = cloneDeep(params)
            console.log(params, 'params')
            params.reviewStandardDTOs.forEach(element => {
                if (element.lvl2Names.length == 1) {
                    element.lvl2Names = element.lvl2Names.map(item => item.value).join(',')
                } else {
                    element.lvl2Names = JSON.stringify(element.lvl2Names)
                }

                element.lvl2Marks = element.lvl2Marks.map(item => item.value).join(',')
            })
            if (params.id) {
                getreviewSchemeUpdate(params).then((res) => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        dialogVisible.value = false
                        ininDate()
                        emit('callBack', "")
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                })
            } else {
                reviewSchemeAdd(params).then((res) => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })

                        dialogVisible.value = false
                        ininDate()
                        emit('callBack', "")
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                })
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
const emit = defineEmits(['callBack']);
const handleClose = (done) => {
    Object.assign(ruleForm, {
        name: '',
        fullMark: '',
        reviewStandardDTOs: [{
            name: '',
            lvl2Names: [{ value: '' }],
            lvl2Marks: [{ value: '' }]
        }]
    })
    delete ruleForm.id;
    emit('callBack', "")
    done()
}
const closeMet = () => {
    ininDate()
    dialogVisible.value = false
}
const ininDate = () => {
    Object.assign(ruleForm, {
        name: '',
        fullMark: '',
        reviewStandardDTOs: [{
            name: '',
            lvl2Names: [{ value: '' }],
            lvl2Marks: [{ value: '' }]
        }]
    })
    delete ruleForm.id;
}
const isJSON = (str) => {
    if (typeof str === 'string') {
        try {
            const obj = JSON.parse(str);
            return typeof obj === 'object' && obj !== null;
        } catch (e) {
            return false;
        }
    }
    return false;
}
const getRuleForm = (i) => {
    for (const key in i) {
        ruleForm[key] = i[key];
    }
    if (i.reviewStandardList && i.reviewStandardList.length > 0) {
        ruleForm.reviewStandardDTOs = i.reviewStandardList.map(item => {
            if (isJSON(item.lvl2Names)) {
                return {
                    name: item.name,
                    lvl2Names: JSON.parse(item.lvl2Names),
                    lvl2Marks: item.lvl2Marks.split(',').map(item => ({ value: item }))
                }
            } else {
                return {
                    name: item.name,
                    lvl2Names: item.lvl2Names.split(',').map(item => ({ value: item })),
                    lvl2Marks: item.lvl2Marks.split(',').map(item => ({ value: item }))
                }
            }

        })
    }
    console.log(ruleForm, 'ruleForm')
}
const addBz = () => {
    ruleForm.reviewStandardDTOs.push({
        name: '',
        lvl2Names: [{ value: '' }],
        lvl2Marks: [{ value: null }]
    })
}
const delBz = (i) => {
    console.log(i, 'i')
    console.log(ruleForm.reviewStandardDTOs, 'ruleForm.reviewStandardDTOs')
    if (ruleForm.reviewStandardDTOs.length == 1 && ruleForm.reviewStandardDTOs[i].lvl2Names.length == 1) {
        return ElMessage({
            message: '标准不能为空',
            type: 'warning',
        })
    } else {
        if (ruleForm.reviewStandardDTOs[i].lvl2Names.length == 1) {
            ruleForm.reviewStandardDTOs.splice(i, 1)
        } else {
            ruleForm.reviewStandardDTOs[i].lvl2Names.splice(ruleForm.reviewStandardDTOs[i].lvl2Names.length - 1, 1)
            ruleForm.reviewStandardDTOs[i].lvl2Marks.splice(ruleForm.reviewStandardDTOs[i].lvl2Marks.length - 1, 1)
        }

    }


}
const addLv2 = (i) => {
    ruleForm.reviewStandardDTOs[i].lvl2Names.push({ value: '' })
    ruleForm.reviewStandardDTOs[i].lvl2Marks.push({ value: null })
}

const validateNumber = (value) => {
    const minValue = 0; // 定义最小值
    if (value < minValue) {
        ruleForm.fullMark = minValue; // 或者设置为空字符串或上一个有效值
    }
    // 使用正则表达式限制小数点后最多4位
    ruleForm.fullMark = value.toString().replace(/[^0-9.]/g, '').replace(/(\.\d{0})\d*/g, '$1');
};




defineExpose({
    getRuleForm
})
</script>

<style scoped lang="scss">
@import url("@/views/achievement/index.scss");

.addText {
    margin-left: 6px;
    cursor: pointer;
    color: #337ab7;
    display: inline-block;
    width: 140px;
}

:deep(.el-table__row) {
    .items-center {
        width: 100%;
    }
}
</style>